package com.icloud.auth.service.impl;

import com.icloud.auth.bean.ClientInfo;
import com.icloud.auth.entity.Client;
import com.icloud.auth.mapper.ClientMapper;
import com.icloud.auth.service.ClientService;
import com.icloud.auth.core.util.client.ClientTokenUtil;
import com.icloud.common.exception.auth.ClientInvalidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 客户端服务
 *
 * @author cuiyl
 */
@Service
public class DBClientService implements ClientService {
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ClientTokenUtil clientTokenUtil;

    @Override
    public String apply(String clientId, String secret) throws Exception {
        Client client = getClient(clientId, secret);
        return clientTokenUtil.generateToken(new ClientInfo(client.getCode(), client.getName(), client.getId().toString()));
    }

    private Client getClient(String clientId, String secret) {
        Client client = clientMapper.findByCode(clientId);
        if (client == null || !client.getSecret().equals(secret)) {
            throw new ClientInvalidException("Client not found or Client secret is error!");
        }
        return client;
    }
}
